package org.farm2.skc.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.farm2.base.db.FarmDbFields;
import org.farm2.base.domain.FarmUserContextLoader;
import org.farm2.base.exception.FarmAppException;
import org.farm2.base.exception.FarmExceptionUtils;
import org.farm2.base.password.FarmPasswordEncoder;
import org.farm2.skc.dao.SkcKnowTagDao;
import org.farm2.skc.dao.SkcTagDao;
import org.farm2.skc.domain.SkcKnowTag;
import org.farm2.skc.domain.SkcTag;
import org.farm2.skc.dto.web.WebTagDto;
import org.farm2.skc.service.SkcTagServiceInter;
import org.farm2.tools.bean.FarmBeanUtils;
import org.farm2.tools.db.DataQuery;
import org.farm2.tools.db.DataResult;
import org.farm2.tools.db.commons.DBRule;
import org.farm2.tools.db.commons.DBRuleList;
import org.farm2.tools.i18n.I18n;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**系统标签 
 * @author cbtg自动生成  2025-2-11 15:32:01 
 */
@Service
@Slf4j
public class SkcTagServiceImpl implements SkcTagServiceInter {
    @Autowired
    private SkcTagDao skcTagDao;
    @Autowired
    private SkcKnowTagDao skcKnowTagDao;

    @Transactional
    @Override
    public SkcTag insertSkcTagEntity(SkcTag skcTag) {
        FarmDbFields.initInsertBean(skcTag, FarmUserContextLoader.getCurrentUser());
        //FarmBeanUtils.runFunctionByBlank(skcTag.getType(), "1", skcTag::setType);
        skcTagDao.insert(skcTag);
       //[tree：树形结构使用]
       //initTreeCode(actions.getId());
        return skcTag;
    }

    @Transactional
    @Override
    public SkcTag editSkcTagEntity(SkcTag skcTag) {
        SkcTag saveSkcTag = getSkcTagById(skcTag.getId());
        FarmExceptionUtils.throwNullEx(saveSkcTag, I18n.msg("系统标签不存在:?", skcTag.getId()));
        saveSkcTag.setId(skcTag.getId());
        saveSkcTag.setCtime(skcTag.getCtime());
        saveSkcTag.setEtime(skcTag.getEtime());
        saveSkcTag.setEuserkey(skcTag.getEuserkey());
        saveSkcTag.setCuserkey(skcTag.getCuserkey());
        saveSkcTag.setState(skcTag.getState());
        saveSkcTag.setNote(skcTag.getNote());
        saveSkcTag.setName(skcTag.getName());
        saveSkcTag.setTagkey(skcTag.getTagkey());
        saveSkcTag.setSortcode(skcTag.getSortcode());
        saveSkcTag.setHaspop(skcTag.getHaspop());
        saveSkcTag.setHastemt(skcTag.getHastemt());
         
        FarmDbFields.initUpdateBean(saveSkcTag, FarmUserContextLoader.getCurrentUser());
        skcTagDao.update(saveSkcTag);
        return saveSkcTag;
    }

    @Transactional
    @Override
    public SkcTag getSkcTagById(String id) {
        return skcTagDao.findById(id);
    }

    @Override
    public List<SkcTag> getSkcTags(DataQuery query) {
        return skcTagDao.queryData(query.setCount(false)).getData(SkcTag.class);
    }



    @Transactional
    @Override
    public DataResult searchSkcTag(DataQuery query) {
        DataResult result = skcTagDao.queryData(query);
        return result;
    }

    @Override
    public int getSkcTagNum(DataQuery query) {
        return skcTagDao.countData(query);
    }


    @Transactional
    @Override
    public void delSkcTag(String id) {
        /*[tree：树形结构使用]
        if ( skcTagDao.findByParentId(id).size() > 0) {
            throw new RuntimeException("不能删除该节点，请先删除其子节点");
        }
        */
        skcTagDao.deleteById(id);
    }
    
    @Override
    public int getNum(DataQuery query) {
        return  skcTagDao.countData(query);
    }


    /* [tree：树形结构使用]
    @Transactional
    @Override*/
    public void autoSort(List<String> ids) {
        int sort = 0;
        for (String id : ids) {
            SkcTag node =  skcTagDao.findById(id);
            if (sort == 0) {
                sort = node.getSortcode();
            }
            node.setSortcode(sort++);
            skcTagDao.update(node);
        }
    }

    @Override
    public List<SkcTag> getTags(String key) {
        DBRuleList rules = DBRuleList.getInstance();
        if (StringUtils.isNotBlank(key)) {
            rules.add(new DBRule("NAME", key, "like"));
        }
        List<SkcTag> tags = skcTagDao.find(rules.toList());
        if (tags.size() > 30) {
            return tags.subList(0, 30);
        } else {
            return tags;
        }
    }

    @Override
    public List<WebTagDto> getUserTags() {
        List<WebTagDto> list = new ArrayList<>();
        List<SkcTag> allTags = skcTagDao.findAll();
        for (SkcTag tag : allTags) {
            WebTagDto dto = new WebTagDto();
            dto.setType("2");
            dto.setKnowNum(getTagKnowNum(tag.getTagkey()));
            dto.setName(tag.getName());
            dto.setTagkey(tag.getTagkey());
            list.add(dto);
        }
        if (list.size() < 30) {
            List<SkcKnowTag> mytags = skcKnowTagDao.queryData(DataQuery.getInstance()//
                    .setSql("TITLE,TYPE,", "SKC_KNOW_TAG")//
                    .addRule(new DBRule("TYPE", "3", "="))//
                    .setPageSize(30)//
                    .setDistinct(true)).getData(SkcKnowTag.class);
            for (SkcKnowTag tag : mytags) {
                WebTagDto dto = new WebTagDto();
                dto.setType("3");
                dto.setKnowNum(getTagKnowNum(tag.getTagkey()));
                dto.setName(tag.getTitle());
                dto.setTagkey(tag.getTagkey());
                list.add(dto);
            }
        }
        return list;
    }

    @Override
    public List<SkcTag> getTagsByName(String name) {
        if (StringUtils.isBlank(name)) {
            return new ArrayList<>();
        }
        return skcTagDao.find(DBRuleList.getInstance().add(new DBRule("NAME", name, "=")).toList());
    }

    private int getTagKnowNum(String tagKey) {
        int num = skcKnowTagDao.countData(new DataQuery().addRule(new DBRule("TAGKEY", tagKey, "=")));
        return num;
    }
}
